import React, { useRef, useState, useEffect } from 'react';
import { Button, message, Space, Modal, Form, Input, InputNumber, Popconfirm, Typography, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { getDepositPage, createDeposit, updateDeposit, deleteDeposit, getDepositById } from '@/services/backend/depositController';
import dayjs from 'dayjs';

const DepositManage: React.FC = () => {
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [viewModalVisible, setViewModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  const [currentRow, setCurrentRow] = useState<any>();
  const actionRef = useRef<ActionType>();

  // 查看存款类型详情
  const handleView = async (record: any) => {
    try {
      const response = await getDepositById(record.depositId);
      if (response.code === 1) {
        setCurrentRow(response.data);
        setViewModalVisible(true);
      } else {
        message.error(response.msg || '获取详情失败');
      }
    } catch (error: any) {
      console.error('获取存款类型详情失败:', error);
      message.error('获取详情失败，请重试');
    }
  };

  // 创建存款产品
  const handleCreate = async (values: any) => {
    setLoading(true);
    try {
      const response = await createDeposit({
        depositName: values.depositName,
        description: values.description,
        termYears: values.termYears || 0,
      });
      if (response.code === 1) {
        message.success('创建成功');
        setCreateModalVisible(false);
        form.resetFields();
        actionRef.current?.reload();
      } else {
        message.error(response.msg || '创建失败');
      }
    } catch (error: any) {
      console.error('创建存款产品失败:', error);
      message.error(error?.data?.msg || '创建失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 更新存款产品
  const handleEdit = async (values: any) => {
    setLoading(true);
    try {
      const response = await updateDeposit({
        depositId: currentRow.depositId,
        depositName: values.depositName,
        description: values.description,
        termYears: values.termYears || 0,
      });
      if (response.code === 1) {
        message.success('更新成功');
        setEditModalVisible(false);
        editForm.resetFields();
        setCurrentRow(undefined);
        actionRef.current?.reload();
      } else {
        message.error(response.msg || '更新失败');
      }
    } catch (error: any) {
      console.error('更新存款产品失败:', error);
      message.error(error?.data?.msg || '更新失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 删除存款产品
  const handleDelete = async (row: any) => {
    setLoading(true);
    try {
      const response = await deleteDeposit(row.depositId);
      if (response.code === 1) {
        message.success('删除成功');
        actionRef.current?.reload();
      } else {
        message.error(response.msg || '删除失败');
      }
    } catch (error: any) {
      console.error('删除存款产品失败:', error);
      message.error(error?.data?.msg || '删除失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const columns: ProColumns<any>[] = [
    {
      title: '存款类型ID',
      dataIndex: 'depositId',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '存款类型名称',
      dataIndex: 'depositName',
      valueType: 'text',
    },
    {
      title: '描述',
      dataIndex: 'description',
      valueType: 'text',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '期限(年)',
      dataIndex: 'termYears',
      valueType: 'digit',
      render: (_, record) => {
        if (record.termYears === 0 || record.termYears === null) {
          return <Tag color="green">活期</Tag>;
        }
        return <Tag color="blue">{record.termYears}年</Tag>;
      },
      hideInSearch: true,
    },
    {
      title: '创建时间区间',
      dataIndex: 'createTimeRange',
      valueType: 'dateRange',
      hideInTable: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      render: (_, record) => record.createTime ? dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') : '-',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size="middle">
          <Typography.Link
            onClick={() => handleView(record)}
          >
            <EyeOutlined /> 查看
          </Typography.Link>
          <Typography.Link
            onClick={() => {
              setCurrentRow(record);
              setEditModalVisible(true);
              editForm.setFieldsValue({
                depositName: record.depositName,
                description: record.description,
                termYears: record.termYears === 0 ? undefined : record.termYears,
              });
            }}
          >
            <EditOutlined /> 编辑
          </Typography.Link>
          <Popconfirm 
            title="确定删除该存款类型？" 
            description="删除后无法恢复，请谨慎操作"
            onConfirm={() => handleDelete(record)}
          >
            <Typography.Link type="danger">
              <DeleteOutlined /> 删除
            </Typography.Link>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<any>
        headerTitle="存款类型管理"
        actionRef={actionRef}
        rowKey="depositId"
        search={{ labelWidth: 120 }}
        toolBarRender={() => [
          <Button type="primary" key="primary" onClick={() => setCreateModalVisible(true)}>
            <PlusOutlined /> 新建存款类型
          </Button>,
        ]}
        request={async (params) => {
          const { createTimeRange, current, pageSize, ...rest } = params;
          console.log('Debug - DepositManage params:', params);
          console.log('Debug - DepositManage createTimeRange:', createTimeRange);
          
          const requestParams = {
            ...rest,
            page: current,
            size: pageSize,
            startTime: createTimeRange?.[0]?.format('YYYY-MM-DD'),
            endTime: createTimeRange?.[1]?.format('YYYY-MM-DD'),
          };
          
          console.log('Debug - DepositManage requestParams:', requestParams);
          
          try {
            const response = await getDepositPage(requestParams);
            console.log('Debug - DepositManage API response:', response);
            
            if (!response) {
              message.error('获取数据失败：服务器无响应');
              return {
                data: [],
                success: false,
                total: 0,
              };
            }
            
            if (response.code !== 1) {
              message.error(`获取数据失败：${response.msg || '未知错误'}`);
              return {
                data: [],
                success: false,
                total: 0,
              };
            }
            
            return {
              data: response.data?.records || [],
              total: response.data?.total || 0,
              success: true,
            };
          } catch (error) {
            console.error('Debug - DepositManage API error:', error);
            message.error('获取数据失败，请检查网络连接');
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={columns}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
      />

      {/* 新建存款类型 */}
      <Modal
        title="新建存款类型"
        open={createModalVisible}
        onCancel={() => setCreateModalVisible(false)}
        footer={null}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleCreate}
          autoComplete="off"
        >
          <Form.Item 
            label="存款类型名称" 
            name="depositName" 
            rules={[
              { required: true, message: '请输入存款类型名称' },
              { max: 50, message: '名称不能超过50个字符' }
            ]}
          > 
            <Input placeholder="请输入存款类型名称" />
          </Form.Item>
          <Form.Item 
            label="描述" 
            name="description" 
            rules={[
              { required: true, message: '请输入描述' },
              { max: 200, message: '描述不能超过200个字符' }
            ]}
          > 
            <Input.TextArea rows={3} placeholder="请输入存款类型描述" />
          </Form.Item>
          <Form.Item 
            label="期限(年)" 
            name="termYears"
            extra="活期存款请留空或填写0，定期存款请填写具体年数"
          >
            <InputNumber 
              min={0} 
              max={50}
              style={{ width: '100%' }} 
              placeholder="活期请留空，定期请输入年数" 
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading}>创建</Button>
            <Button style={{ marginLeft: 8 }} onClick={() => setCreateModalVisible(false)}>取消</Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑存款类型 */}
      <Modal
        title="编辑存款类型"
        open={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        footer={null}
        destroyOnClose
      >
        <Form 
          form={editForm} 
          layout="vertical" 
          onFinish={handleEdit}
          autoComplete="off"
        >
          <Form.Item 
            label="存款类型名称" 
            name="depositName" 
            rules={[
              { required: true, message: '请输入存款类型名称' },
              { max: 50, message: '名称不能超过50个字符' }
            ]}
          > 
            <Input placeholder="请输入存款类型名称" />
          </Form.Item>
          <Form.Item 
            label="描述" 
            name="description" 
            rules={[
              { required: true, message: '请输入描述' },
              { max: 200, message: '描述不能超过200个字符' }
            ]}
          > 
            <Input.TextArea rows={3} placeholder="请输入存款类型描述" />
          </Form.Item>
          <Form.Item 
            label="期限(年)" 
            name="termYears"
            extra="活期存款请留空或填写0，定期存款请填写具体年数"
          >
            <InputNumber 
              min={0} 
              max={50}
              style={{ width: '100%' }} 
              placeholder="活期请留空，定期请输入年数" 
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading}>保存</Button>
            <Button style={{ marginLeft: 8 }} onClick={() => setEditModalVisible(false)}>取消</Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 查看存款类型详情 */}
      <Modal
        title="存款类型详情"
        open={viewModalVisible}
        onCancel={() => setViewModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setViewModalVisible(false)}>关闭</Button>
        ]}
        destroyOnClose
      >
        {currentRow && (
          <div>
            <p><strong>存款类型ID：</strong>{currentRow.depositId}</p>
            <p><strong>存款类型名称：</strong>{currentRow.depositName}</p>
            <p><strong>描述：</strong>{currentRow.description}</p>
            <p><strong>期限：</strong>
              {currentRow.termYears === 0 || currentRow.termYears === null ? '活期' : `${currentRow.termYears}年`}
            </p>
            <p><strong>创建时间：</strong>{dayjs(currentRow.createTime).format('YYYY-MM-DD HH:mm:ss')}</p>
            <p><strong>更新时间：</strong>{dayjs(currentRow.updateTime).format('YYYY-MM-DD HH:mm:ss')}</p>
            <p><strong>状态：</strong>
              {currentRow.isDeleted ? 
                <Tag color="red">已删除</Tag> : 
                <Tag color="green">正常</Tag>
              }
            </p>
          </div>
        )}
      </Modal>
    </PageContainer>
  );
};

export default DepositManage; 